import classnames from 'classnames'
import type { CSSProperties, FC } from 'react'
import React from 'react'
import { withNativeProps } from '../../../src/utils/native-props'
import { type ComponentProps } from '../../global/common-style'

const classPrefix = `gd-mask`

export type MaskProps = {
  /**
   * 是否显示
   * @type {boolean}
   * @memberof
   */
  open: boolean
  /**
   * 关闭回调
   * @type {Function}
   * @memberof
   */
  onClose?: () => void
  /**
   * 是否开启蒙层
   * @type {boolean}
   * @memberof
   */
  mask?: boolean
  /**
   * 点击蒙层是否关闭
   * @type {boolean}
   * @memberof
   */
  maskClosable?: boolean
  /**
   * mask 的style
   * @type {CSSProperties}
   */
  maskStyle?: CSSProperties
} & ComponentProps &
  React.PropsWithChildren<object>

export const Mask: FC<MaskProps> = (props) => {
  const {
    open,
    onClose,
    mask = true,
    maskClosable = true,
    maskStyle,
    className,
    style,
  } = props

  function onTouchMove(event: React.TouchEvent<HTMLDivElement>) {
    event.stopPropagation()
  }

  function onMaskClick() {
    // eslint-disable-next-line no-unused-expressions
    maskClosable && onClose && onClose()
  }

  function getClassName() {
    const classNameArray = [classPrefix, className]
    if (!open) {
      classNameArray.push(`${classPrefix}-hide`)
    }
    classNameArray.push(`${classPrefix}-center`)

    return classnames(...classNameArray)
  }

  return withNativeProps(
    props,
    <div
      className={getClassName()}
      onTouchMove={(event) => {
        onTouchMove(event)
      }}
      style={style}
    >
      {mask && (
        <div
          onClick={() => {
            onMaskClick()
          }}
          className={`${classPrefix}-mask`}
          style={maskStyle}
        />
      )}
      <div className={`${classPrefix}-content`}>{props.children}</div>
    </div>
  )
}
